package com.example.demo.exception;

import com.example.demo.common.Result;
import com.example.demo.common.ResultCode;
import com.example.demo.util.TraceIdUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.sql.SQLException;
import java.util.stream.Collectors;

/**
 * 全局异常处理器
 * 自动捕获所有Controller层抛出的异常并封装到Result类
 * 
 * @author zhang
 * @date 2024
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    
    /**
     * 将TraceId添加到响应头（所有异常处理都会调用）
     */
    private void addTraceIdToResponse(HttpServletResponse response) {
        if (response != null && !response.isCommitted()) {
            String traceId = TraceIdUtil.getTraceId();
            if (traceId != null) {
                response.setHeader("X-Trace-Id", traceId);
            }
        }
    }
    
    /**
     * 处理参数校验异常（@Valid注解）
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request, HttpServletResponse response) {
        addTraceIdToResponse(response);
        String errorMessage = e.getBindingResult().getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining(", "));
        logger.warn("参数校验失败: {}", errorMessage);
        return Result.create().error(ResultCode.PARAM_ERROR.getCode(), errorMessage);
    }
    
    /**
     * 处理绑定异常
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<?> handleBindException(BindException e, HttpServletRequest request, HttpServletResponse response) {
        addTraceIdToResponse(response);
        String errorMessage = e.getBindingResult().getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining(", "));
        logger.warn("绑定失败: {}", errorMessage);
        return Result.create().error(ResultCode.PARAM_ERROR.getCode(), errorMessage);
    }
    
    /**
     * 处理约束违反异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<?> handleConstraintViolationException(ConstraintViolationException e, HttpServletRequest request, HttpServletResponse response) {
        addTraceIdToResponse(response);
        String errorMessage = e.getConstraintViolations().stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.joining(", "));
        logger.warn("约束违反: {}", errorMessage);
        return Result.create().error(ResultCode.PARAM_ERROR.getCode(), errorMessage);
    }
    
    /**
     * 处理认证异常
     */
    @ExceptionHandler(org.springframework.security.core.AuthenticationException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public Result<?> handleAuthenticationException(org.springframework.security.core.AuthenticationException e, HttpServletRequest request, HttpServletResponse response) {
        addTraceIdToResponse(response);
        logger.warn("认证失败: {}", e.getMessage());
        return Result.create().error(ResultCode.UNAUTHORIZED.getCode(), "认证失败，请先登录");
    }
    
    /**
     * 处理权限不足异常
     */
    @ExceptionHandler(AccessDeniedException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public Result<?> handleAccessDeniedException(AccessDeniedException e, HttpServletRequest request, HttpServletResponse response) {
        addTraceIdToResponse(response);
        logger.warn("权限不足: {}", e.getMessage());
        return Result.create().error(ResultCode.FORBIDDEN.getCode(), "权限不足，无法访问");
    }
    
    /**
     * 处理非法参数异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<?> handleIllegalArgumentException(IllegalArgumentException e, HttpServletRequest request, HttpServletResponse response) {
        addTraceIdToResponse(response);
        logger.warn("非法参数: {}", e.getMessage());
        return Result.create().error(ResultCode.PARAM_ERROR.getCode(), e.getMessage());
    }
    
    /**
     * 处理SQL异常
     */
    @ExceptionHandler(SQLException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<?> handleSQLException(SQLException e, HttpServletRequest request, HttpServletResponse response) {
        addTraceIdToResponse(response);
        logger.error("数据库操作异常", e);
        return Result.create().error(ResultCode.DATABASE_ERROR.getCode(), "数据库操作失败");
    }
    
    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public Result<?> handleBusinessException(BusinessException e, HttpServletRequest request, HttpServletResponse response) {
        addTraceIdToResponse(response);
        logger.warn("业务异常: {}", e.getMessage());
        return Result.create().error(e.getCode(), e.getMessage());
    }
    
    /**
     * 处理所有其他异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<?> handleException(Exception e, HttpServletRequest request, HttpServletResponse response) {
        addTraceIdToResponse(response);
        logger.error("未知异常: {}", e.getMessage(), e);
        return Result.create().error(ResultCode.INTERNAL_ERROR.getCode(), "系统异常，请联系管理员");
    }
}

